package com.apobates.forum.trident.controller.admin;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.trident.controller.form.BoardGroupForm;
import com.apobates.forum.trident.exception.ResourceNotFoundException;
import com.apobates.forum.trident.fileupload.ImageStorageExecutor;
import com.apobates.forum.core.api.service.BoardGroupService;
import com.apobates.forum.core.entity.BoardGroup;
import com.apobates.forum.utils.CommonBean;
import com.apobates.forum.utils.Commons;
/**
 * 版块卷控制器
 * 
 * @author xiaofanku@live.cn
 * @since 20190321
 */
@Controller
@RequestMapping(value = "/admin/board/group")
public class AdminBoardGroupController {
	@Autowired
	private BoardGroupService boardGroupService;
	@Autowired
	private ImageStorageExecutor imageStorageExecutor;
	private final static Logger logger = LoggerFactory.getLogger(AdminBoardGroupController.class);
	
	//版块组(卷)
	@GetMapping(path="/")
	public String listPage(HttpServletRequest request, Model model) {
		List<BoardGroup> rs = boardGroupService.getAll().collect(Collectors.toList());
		rs.add(BoardGroup.getDefault()); //默认版块组
		model.addAttribute("rs", rs);
		return "admin/board_volumes/index";
	}
	
	//编辑版块组(卷)
	@GetMapping(path="/edit")
	public String boardVolumesForm(
			@RequestParam(name="id", required=false, defaultValue="-1") int id, 
			HttpServletRequest request, 
			Model model) {
		if(id==0){
			throw new ResourceNotFoundException("默认版块组(卷)不需要编辑");
		}
		BoardGroupForm form = new BoardGroupForm();
		BoardGroup bg = boardGroupService.get(id).orElse(BoardGroup.empty());
		form.setRecord(id);
		form.setStatus(bg.isStatus());
		//
		form.setTitle(bg.getTitle());
		form.setDescription(bg.getDescription());
		form.setImageAddr(bg.getImageAddr()); //编码后的图标图片地址|解码由标签负责
		
		form.setRanking(bg.getRanking()+"");
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/board_volumes/edit";
	}
	@PostMapping(path="/edit")
	public String boardVolumesAction(@ModelAttribute("form") BoardGroupForm form, HttpServletRequest request, Model model) {
		BoardGroup bg = new BoardGroup();
		bg.setTitle(form.getTitle());
		bg.setDescription(form.getDescription());
		bg.setStatus(form.getBooleanStatus());
		bg.setRanking(form.getIntegerRanking());
		//------------------------------------------------------------编码图标图片的地址
		String icoImageAddr = form.getEncodeIcoAddr(imageStorageExecutor);
		if(icoImageAddr != null){
			bg.setImageAddr(icoImageAddr);
		}
		//------------------------------------------------------------
		boolean symbol = false;
		String errMsg=null;
		try{
			if(form.isUpdate()) {
				symbol = boardGroupService.edit(form.getIntegerRecord(), bg).orElse(false);
			}else {
				symbol = boardGroupService.create(bg.getTitle(), bg.getDescription(), bg.getImageAddr(), bg.isStatus(), bg.getRanking()).isPresent();
			}
		}catch(IllegalStateException e){
			errMsg=e.getMessage();
		}
		if(symbol) {
			return "redirect:/admin/board/group/";
		}
		model.addAttribute("errors", Commons.optional(errMsg, form.getActionTitle()+"版块组(卷)操作失败"));
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/board_volumes/edit";
	}
	//所有组(卷)
	@GetMapping(path="/json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<Integer,String> getAllForJson(HttpServletRequest request, Model model){
		//包含所有状态的还有默认的
		return boardGroupService.getAllContainsDefault().collect(Collectors.toMap(BoardGroup::getId, BoardGroup::getTitle));
	}
	//查看指定的版块组(卷)的名称
	@GetMapping(path="/list.json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<Integer,String> getAllForIdJson(
			@RequestParam("ids") String idString, 
			HttpServletRequest request, 
			Model model){
		return boardGroupService.getAllById(Commons.toIntegerSet(idString));
	}
	//加载版块组的标题
	@GetMapping(path="/title", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public CommonBean getBoardGroupTitle(
			@RequestParam("id")int id, 
			HttpServletRequest request,
			Model model){
		if(id == -1){
			return new CommonBean(-1, "所有");
		}
		if(id == 0){
			return new CommonBean(0, "默认版块组");
		}
		String title="版块组(卷)";
		Optional<BoardGroup> board = boardGroupService.get(id);
		if(board.isPresent()){
			title = board.get().getTitle();
		}
		return new CommonBean(id, title);
	}
}
